<template>
    <Form ref="accountLoginForm" :model="accountLoginForm" :rules="ruleValidate" @keydown.enter.native="handleSubmit">
        <FormItem prop="userName">
            <Input type="text" size="large" v-model="accountLoginForm.userName" clearable placeholder="用户名" autocomplete="off">
                <Icon type="ios-contact" slot="prefix" />
            </Input>
        </FormItem>
        <FormItem prop="password">
            <Input type="password" size="large" v-model="accountLoginForm.password" clearable placeholder="密码" autocomplete="off">
                <Icon type="md-lock" slot="prefix"/>
            </Input>
        </FormItem>
        <FormItem>
            <Checkbox v-model="rememberMe">自动登录</Checkbox>
            <Button style="float: right;" type="text" to="javascript: void(0);">忘记密码</Button>
        </FormItem>
    </Form>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'AccountLoginForm',
  data () {
    const customUserNameRules = (rule, value, callback) => {
      if (value === '') {
        this.changeDataValid(false)
        callback(new Error('用户名不能为空'))
      } else {
        this.changeDataValid(true)
        callback()
      }
    }
    const customPasswordRules = (rule, value, callback) => {
      if (value === '') {
        this.changeDataValid(false)
        callback(new Error('密码不能为空'))
      } else {
        this.changeDataValid(true)
        callback()
      }
    }
    return {
      accountLoginForm: {
        userName: '',
        password: ''
      },
      ruleValidate: {
        userName: [{
          validator: customUserNameRules,
          trigger: 'blur'
        }],
        password: [{
          validator: customPasswordRules,
          trigger: 'blur'
        }]
      },
      rememberMe: false
    }
  },
  methods: {
    ...mapActions([
      'changeDataValid' // 将 `this.changeDataValid(status)` 映射为 `this.$store.dispatch('changeDataValid',status)`
    ]),
    handleSubmit () {
      this.$refs.accountLoginForm.validate(valid => {
        if (valid) {
          this.$emit('on-success-valid', {
            userName: this.accountLoginForm.userName,
            password: this.accountLoginForm.password
          })
        }
      })
    }
  }
}
</script>
